package com.hursing.tractor.baseview;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import com.hursing.tractor.model.Card;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;

public class UICardView extends UIView {

	public static final int ALIGN_CENTER = 0;
	public static final int ALIGN_LEFT = 1;
	public static final int ALIGN_RIGHT = 2;
	
	protected static Rect mCardSrcBounds;
	protected static Bitmap[] mCardBitmaps;
	private int mAlign;
	protected int mCardWidth;
	private Rect mCardDstBound = new Rect();
	protected LinkedList<Card> mCards = new LinkedList<Card>();
	
	@Override
	public UIView frame(Rect rect) {
		super.frame(rect);
		mCardDstBound.top = mFrame.top;
		mCardDstBound.bottom = mFrame.bottom;
		mCardWidth = mFrame.height() * mCardSrcBounds.width() / mCardSrcBounds.height();
		return this;
	}
	
	@Override
	public UICardView toCardView() { return this; }
	
	public UICardView setAlign(int align) {
		mAlign = align;
		return this;
	}
	
	public UICardView cards(Collection<Card> cards) {
		mCards.clear();
		if (cards != null) {
			mCards.addAll(cards);
		}
		invalidate();
		return this;
	}
	
	public UICardView setCardBitmaps(Bitmap[] bitmaps) {
		if (mCardBitmaps == null) {
			mCardBitmaps = bitmaps;
			mCardSrcBounds = new Rect(0, 0, mCardBitmaps[0].getWidth(), mCardBitmaps[0].getHeight());
		}
		return this;
	}
	
	@Override
	protected void doDraw (Canvas canvas) {
		drawCards(canvas, mCards);
	}
	
	protected void drawCards(Canvas canvas, List<Card> cards) {
		int size = cards.size();
		if (size == 0) {
			return;
		}
		int interval = mCardWidth;
		if (cards.size() * mCardWidth > mFrame.width()) {
			mCardDstBound.left = mFrame.left;
			// 保证最后一张牌能画全
			interval = (mFrame.width() - mCardWidth) / (size - 1);
		} else {
			if (mAlign == ALIGN_CENTER) {
				mCardDstBound.left = mFrame.centerX() - mCardWidth * size / 2;
			} else if (mAlign == ALIGN_LEFT) {
				mCardDstBound.left = mFrame.left;
			} else if (mAlign == ALIGN_RIGHT) {
				mCardDstBound.left = mFrame.right - mCardWidth * size;
			}
		}
		
		for (int i = 0; i < size; i++) {
			mCardDstBound.right = mCardDstBound.left + mCardWidth;
			Card card = cards.get(i);
			canvas.drawBitmap(mCardBitmaps[card.index()], mCardSrcBounds, mCardDstBound, null);
			mCardDstBound.left += interval;
		}
	}

}
